package com.megvii.koala.data.manager;

import android.content.Context;

import com.megvii.corelib.data.BeanManager;
import com.megvii.corelib.util.SharedPreferenceTool;
import com.megvii.koala.data.bean.NetLockerBean;
import com.megvii.koala.locker.NetLockerController;

/**
 * Created by linyue on 16/1/8.
 */
public class NetLockerManager extends BeanManager<NetLockerBean>
{
    public static final String KEY_SELECTION_ADDRESS = "NET_LOCKER_SELECTION_ADDRESS";

    public static final String KEY_SELECTION_TOKEN = "NEW_LOCKER_SELECTION_TOKEN";

    private Context context;

    private NetLockerController controller;

    private String selectionId = null;

    public void init(Context context)
    {
        this.context = context;
        controller = new NetLockerController();
        controller.init();
        clear();
        String selectionAddress = SharedPreferenceTool
                .getStringValueByKey(context, KEY_SELECTION_ADDRESS, null);
        String selectionToken = SharedPreferenceTool
                .getStringValueByKey(context, KEY_SELECTION_TOKEN , null);
        if (selectionAddress != null)
        {
            NetLockerBean netLockerBean = new NetLockerBean(selectionAddress);
            if(selectionToken != null) {
                netLockerBean.setToken(selectionToken);
            }
            update(netLockerBean);
            setSelectionId(netLockerBean.id);
        }
    }

    public void release()
    {
        if (controller != null)
        {
            controller.release();
        }
        controller = null;
        clear();
    }

    public void openDoor()
    {
        final NetLockerBean bean = getSelection();
        if (bean != null)
        {
            new Thread()
            {
                public void run()
                {
                    controller.openDoor(bean.address);
                    try
                    {
                        sleep(1000);
                    }
                    catch (InterruptedException e)
                    {
                        e.printStackTrace();
                    }
                    controller.closeDoor(bean.address);
                }
            }.start();
        }
    }

    public void setSelectionId(String id)
    {
        this.selectionId = id;
        NetLockerBean selection = getSelection();
        if (selection != null)
        {
            SharedPreferenceTool.saveStringValue(context, KEY_SELECTION_ADDRESS, selection.address);
            SharedPreferenceTool.saveStringValue(context, KEY_SELECTION_TOKEN, selection.token);
        }
    }

    public NetLockerBean getSelection()
    {
        return get(selectionId);
    }

    public void clearSelection()
    {
        this.selectionId = null;
        SharedPreferenceTool.removeStringValue(context, KEY_SELECTION_ADDRESS);
        SharedPreferenceTool.removeStringValue(context, KEY_SELECTION_TOKEN);
    }
}
